<template>
  <div id="chatpage" style="width: 100%; height: 100vh">
    <!-- <input type="text" v-model="acc" placeholder="账号">
    <input type="text" v-model="chatacc" placeholder="对方">
    <button @click="dengji">登记</button> -->
    <div class="content">
      <div class="right-item" v-loading="loading">
        <div class="right-header">当前会话</div>
        <div
          v-for="(item, index) in chatarr"
          class="chater-item"
          @click="changechat(item, index)"
          :class="index == nowchat ? 'activechat' : ''"
          :key="index"
        >
          <el-badge :is-dot="item.msgnum > 0" class="item">
            <el-image
              style="width: 40px; height: 40px; border-radius: 50%"
              :src="item.userPhoto"
              fit="scale-down"
            ></el-image>
          </el-badge>
          <div class="chatinfo">
            <span>{{ item.userName }}</span>
            <div class="txt" v-html="chatcont(item)"></div>
          </div>
        </div>
      </div>
      <div class="left-item">
        <div class="left-header">
          <span>{{ chatobj.userName ? chatobj.userName : "请选择用户" }}</span>
          <span>会话中</span>
        </div>
        <div class="left-content">
          <div class="chat-con">
            <div
              ref="chatbox"
              v-loading="chatloading"
              element-loading-spinner="el-icon-loading"
              class="chatmsgdiv"
            >
              <div
                v-for="(item, index) in msglist"
                :key="index"
                :class="item.senderid == selfobj.userTel ? 'mymsgdiv' : ''"
                class="chat-item-msg"
              >
                <img :src="item.headerphoto" alt="" />
                <div class="msgtxt">
                  <span>{{ item.sendername }}</span>
                  <div v-if="item.msg" v-html="item.msg" class="msgdiv"></div>
                  <div v-if="item.msgimg" class="msgdiv">
                    <img :src="item.msgimg" alt="" />
                  </div>
                </div>
              </div>
            </div>
            <div class="chatsenddiv">
              <quill-editor
                v-model="content"
                ref="myQuillEditor"
                :options="editorOption"
                @blur="onEditorBlur($event)"
                @focus="onEditorFocus($event)"
                @change="onEditorChange($event)"
              >
              </quill-editor>
              <el-upload
                id="iviewUp"
                :show-upload-list="false"
                :on-success="handleSuccessQuill"
                :format="['jpg', 'jpeg', 'png', 'gif']"
                :max-size="2048"
                multiple
                :action="uploadRichTextImg"
                style="display: none"
              >
                <Button icon="ios-cloud-upload-outline"></Button>
              </el-upload>
              <i @click="historyshow()" class="el-icon-time"></i>
              <el-button
                class="sendbtn"
                type="primary"
                @click="sendmsg()"
                size="mini"
                round
                icon="el-icon-position"
              ></el-button>
            </div>
          </div>
          <div class="chat-con-r">
            <transition name="el-zoom-in-center">
              <div v-show="drawer" class="history">
                <div style="text-align: center">会话记录</div>
                <div
                  v-for="(item, index) in historylist"
                  :key="index"
                  class="his-item"
                >
                  <p>
                    <span>{{ item.userName }}</span>
                    <span style="margin-left: 20px">{{ item.time }}</span>
                  </p>
                  <div v-html="item.chatContent"></div>
                </div>
              </div>
            </transition>
            <transition name="el-zoom-in-center">
              <div v-show="!drawer">
                <div style="text-align: center">用户信息</div>
                <div slot="empty">
                  <el-empty
                    v-if="showempty"
                    description="请选择会话对象"
                  ></el-empty>
                </div>

                <div v-show="chatinfo.userName" class="chatuserinfo">
                  <p>{{ chatinfo.userName }}</p>
                  <img :src="chatinfo.userPhoto" alt="" />
                  <p>电话：{{ chatinfo.userTel }}</p>
                </div>
              </div>
            </transition>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import EditorBar from "../components/WangEnduit.vue";
import filtering from "../assets/js/filtering";
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import * as Quill from "quill"; // 引入编辑器
import ImageResize from "quill-image-resize-module";
Quill.register("modules/imageResize", ImageResize);
import quillEmoji from "quill-emoji";
import "quill-emoji/dist/quill-emoji.css";
Quill.register("modules/quillEmoji", quillEmoji);

export default {
  components: {
    quillEditor,
  },
  data() {
    return {
      loading: false, //会话列表加载
      chatloading: false, //聊天框加载
      showempty: true,
      drawer: false, //历史消息
      nowchat: -1,
      selfobj: {},
      chatacc: "",
      historylist: [],
      chatobj: {},
      chatinfo: {},
      sensitiveArr:'',//敏感词汇
      msglist: [], //聊天消息
      chatarr: [], //会话列表
      content: "",
      uploadRichTextImg: "http://112.74.185.144:8000/api/common/uploadfile",
      editorOption: {
        placeholder: "请在这里输入",
        modules: {
          "emoji-toolbar": true,
          "emoji-shortname": true,
          toolbar: {
            container: [
              // [{ size: ["small", false, "large", "huge"] }], // 字体大小
              // // [{ header: [1, 2, 3, 4, 5, 6, false] }], //几级标题
              // [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
              // [{ font: [] }], //字体
              // [{ align: [] }], //对齐方式
              // ["clean"], //清除字体样式
              ["emoji"], //表情包
              ["image"], //上传图片、上传视频
            ],
            handlers: {
              image: function (value) {
                // 对图片进行改造，默认是通过base64 ,现通过iview 去传。
                if (value) {
                  console.log("重写了");
                  document.querySelector("#iviewUp input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
          imageResize: {
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white",
              width: "50px",
              height: "50px",
            },
            modules: ["Resize", "DisplaySize", "Toolbar"],
          },
        },
      },
    };
  },
  sockets: {
    connect() {
      console.log("连接成功");
      this.$socket.emit("login", {
        loginer: sessionStorage.getItem("userTel"),
        kefu: 0, //不是客服
      });
    },
    disconnect() {
      console.log("断开连接");
    },
    relogin(data) {
      console.log(data, 24);
    },
    message(data) {
      console.log("ws 收到服务器消息", data);
      this.msglist.push(data);
      this.updatescorll();
    },
    messagetip(data) {
      let issave = false;
      // console.log(data,222);
      this.chatarr.forEach((item) => {
        if (item.phone == data.senderid) {
          item.msgnum += 1;
          item.msgtxt = data.msg;
          item.msgimg = data.msgimg;
          issave = true;
        }
      });
      if (!issave) {
        this.chatarr.push({
          msgnum: 1,
          msgtxt: data.msg,
          userPhoto: data.headerphoto,
          userName: data.sendername,
          phone: data.senderid,
        });
      }

      // this.getchatarr()
    },
  },
  methods: {
    getacchistory() {
      this.$axios({
        url: "api/chat/getmsg",
        method: "GET",
        params: {
          sendid: this.chatobj.phone,
          findkefu: 0,
        },
      }).then((data) => {
        console.log(data, 215);
        this.historylist = data.data.data;
      });
    },
    historyshow() {
      this.drawer = !this.drawer;
      if (this.nowchat > -1 && this.drawer) {
        this.getacchistory();
      }
    },
    dengji() {
      this.$socket.emit("login", {
        loginer: sessionStorage.getItem("userTel"),
        kefu: 0, //不是客服
      });
    },
    changechat(item, id) {
      this.nowchat = id;
      this.chatobj = item;
      item.msgnum = 0;
      this.$socket.emit("onchat", {
        receiverPhone: item.phone,
      });
      this.getchatarr(); //更新会话列表
      this.chatloading = true;
      this.$axios({
        url: "api/userTabel/userinfo",
        params: {
          userTel: this.chatobj.phone,
        },
        method: "get",
      })
        .then((data) => {
          // console.log(this.chatobj.phone, this.selfobj.phone, 208);
          this.chatinfo = data.data.data[0];
          this.getacchistory(); //更新历史记录
          this.showempty = false;
          this.getmsglist();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getmsglist() {
      console.log(this.chatobj.phone,305);
      this.$axios({
        url: "api/chat/getmsg",
        params: {
          sendid: this.selfobj.userTel,
          receiverPhone: this.chatobj.phone,
          findkefu: 1,
        },
        method: "get",
      })
        .then((resp) => {
          this.msglist = [];
          console.log(resp.data.data, "聊天记录");
          resp.data.data.forEach((item) => {
            this.msglist.push({
              msg: item.chatContent,
              msgimg: item.msgimg,
              senderid: item.sendPhone,
              sendername: item.userName,
              headerphoto: item.userPhoto,
            });
          });
          this.chatloading = false;
          this.updatescorll();
          // this.msglist = resp.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleSuccessQuill(res) {
      console.log(res, 152);
      // 获取富文本组件实例
      const quill = this.$refs.myQuillEditor.quill;
      // 如果上传成功
      if (res) {
        // 获取光标所在位置
        const length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, "image", res.data);
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        // 提示信息，需引入Message
        console.log("图片插入失败");
      }
    },
    onEditorReady(editor) {
      // 准备编辑器
      console.log(editor);
    },
    onEditorBlur() {}, // 失去焦点事件
    onEditorFocus() {}, // 获得焦点事件
    onEditorChange() {
      console.log(this.content);
    }, // 内容改变事件
    escapeStringHTML(str) {
      str = str.replace(/&lt;/g, "<");
      str = str.replace(/&gt;/g, ">");
      return str;
    },
    sendmsg() {
      let newmgs = filtering(this.sensitiveArr, this.content);
      let a = {
        msg: newmgs,
        msgimg: "",
        type: 0,
        senderid: this.selfobj.userTel,
        sendername: this.selfobj.userName,
        receiverPhone: this.chatobj.phone,
        headerphoto: this.selfobj.photo,
      };
      console.log(a);
      this.$socket.emit("send_msg", a);
      this.msglist.push(a);
      this.updatescorll();
      this.content = "";
    },
    updatescorll() {
      let chatbox = this.$refs.chatbox;
      console.log(chatbox);
      this.$nextTick(() => {
        chatbox.scrollTop = chatbox.scrollHeight;
      });
    },
    getchatarr() {
      this.$axios({
        url: "api/chat/getchatlist",
        method: "GET",
        params: {
          sendid: this.selfobj.userTel,
          type: 0,
        },
      })
        .then((data) => {
          console.log(data, 219, "会话列表");
          this.chatarr = data.data.data;
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
  mounted() {
    console.log(this.$route.params, 393);
    let shopttel = this.$route.params.id;
    this.$axios({
      url: 'api/sensitiveTable/get',
      method: "GET"
    }).then((data) => {
      console.log(data,451);

      this.sensitiveArr=data.data.data.map((i)=>{
        return i.sensitiveField
      })
      // console.log(this.sensitiveArr,457);
    }).catch ((err) => {
      console.log(err);
    })
    this.$axios({
      //获取用户信息
      url: "api/userTabel/userinfo",
      params: {
        userTel: sessionStorage.getItem("userTel"),
      },
      method: "GET",
    })
      .then((data) => {
        this.selfobj = data.data.data[0];
        console.log(this.selfobj, "用户信息");
        this.loading = true;
        this.dengji();
        this.$axios({
          url: "api/chat/getchatlist",
          method: "GET",
          params: {
            sendid: this.selfobj.userTel,
            type: 0, //查询消息列表
          },
        })
          .then((data) => {
            console.log(data, 219);
            this.chatarr = data.data.data;
            // let
            let issave = false;
            this.chatloading = true;
            this.$axios({
              url: "api/userTabel/userinfo",
              params: {
                userTel: shopttel,
              },
              method: "get",
            })
              .then((data) => {
                // console.log(this.chatobj.phone, this.selfobj.phone, 208);
                this.chatinfo = data.data.data[0];
                console.log(this.chatinfo,this.chatarr,448);
                this.chatarr.forEach((item, index) => {
                  if (item.phone == shopttel) {
                    issave = true;
                    this.nowchat = index;
                    this.chatobj = item;
                   
                  }
                });
                if (!issave) {
                  // issave=false
                  this.chatarr.unshift({
                    msgnum:0,
                    msgimg:'',
                    msgtxt:'',
                    phone:this.chatinfo.userTel,
                    userName:this.chatinfo.userName,
                    userPhoto:this.chatinfo.userPhoto
                  })
                  this.nowchat = 0;
                    this.chatobj = this.chatarr[0];

                }

                this.getacchistory(); //更新历史记录
                this.showempty = false;
                this.getmsglist();
              })
              .catch((err) => {
                console.log(err);
              });

            this.loading = false;
          })
          .catch((err) => {
            console.log(err);
          });
      })
      .catch((err) => {
        console.log(err);
      });
  },
  created(){
    document.title = '用户聊天'
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill;
    },
    chatcont(){
      return (item)=>{
        if(item.msgtxt){
          return item.msgtxt;
        }else if(item.msgimg) {
          return '图片'
        }else{
          return ''
        }
      }
    }
  },
};
</script>

<style scoped>
#chatpage {
  width: 100%;
  height: 100vh;
  background: url(http://112.74.185.144:8000/files/26o1666278222.gif) 0 0
    no-repeat;
  background-size: cover;
}
.quill-editor {
  height: 148px;
}
#chatpage /deep/ .ql-editor img {
  display: inline-block;
  width: 100px;
  height: 100px;
}
#chatpage /deep/ .ql-container,
.ql-snow {
  border: 0 !important;
}
#chatpage /deep/ .ql-toolbar.ql-snow {
  border-right: 0;
  border-left: 0;
}

.content {
  box-sizing: border-box;
  padding: 10px;
  display: flex;
  height: 660px;
  width: 1200px;
  margin: 0 auto;
}

.chater-item {
  width: 100%;
  height: 60px;
  display: flex;
  box-sizing: border-box;
  padding-left: 10px;
  align-items: center;
  position: relative;
  transition: background-color 0.5s;
  border-bottom: 1px solid rgb(241 227 227);
  cursor: pointer;
}

.right-header {
  height: 50px;
  line-height: 50px;
  box-sizing: border-box;
  padding-left: 17px;
}

.right-item {
  background-color: white;
  height: 100%;
  width: 250px;
  overflow-x: hidden;
  scrollbar-width: none;
  border-radius: 5px;
  padding: 0;
}

.chatinfo > span:nth-child(1) {
  font-size: 12px;
  display: block;
}

.chatinfo > div:nth-child(2) {
  font-size: 12px;
  color: rgb(0, 0, 0, 0.3);
}
#chatpage /deep/ .chatinfo > div p {
  margin: 0;
}

.activechat {
  background-color: rgb(230, 241, 255);
  border: 0;
}

.activechat::after {
  content: "";
  display: block;
  width: 3px;
  height: 100%;
  position: absolute;
  right: 0;
  background-color: rgb(26, 125, 255);
}

.left-item {
  height: 100%;
  width: 800px;
  background-color: white;
  border-radius: 5px;
  margin-left: 10px;
}

.left-header {
  width: 100%;
  height: 50px;
  line-height: 50px;
  box-sizing: border-box;
  padding-left: 10px;
  border-bottom: 1px solid rgb(241 227 227);
}

.left-header > span:nth-child(1) {
  font-size: 15px;
  margin-right: 10px;
}

.left-header > span:nth-child(2) {
  font-size: 12px;
  color: rgb(0, 0, 0, 0.2);
}

.left-content {
  display: flex;
  height: calc(100% - 50px);
}

.chat-con {
  height: 100%;
  width: 600px;
  border-right: 1px solid rgb(0, 0, 0, 0.2);
}

.chatmsgdiv {
  background-color: rgb(249, 249, 249);
  width: 100%;
  height: 400px;
  overflow-x: hidden;
  overflow-y: auto;
  box-sizing: border-box;
  padding-top: 20px;
  padding-left: 10px;
  scrollbar-width: none;
}
.chatmsgdiv::-webkit-scrollbar {
  display: none;
}
.chatsenddiv {
  width: 100%;
  height: calc(100% - 400px);
  background: white;
  position: relative;
}

.chat-item-msg {
  width: 100%;
  display: flex;
  margin-bottom: 20px;
}

.chat-item-msg > img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.msgdiv {
  margin-top: 5px;
  background: white;
  padding: 5px;
  border-radius: 5px;
  max-width: 250px;
  width: fit-content;
  box-shadow: 1px 1px 4px 2px #ccc;
  white-space: normal;
  word-break: break-all;
  overflow: hidden;
}
.txt {
  width: 100%;
  white-space: normal;
  word-break: break-all;
  overflow: hidden;
}
.msgtxt > span {
  color: rgb(0, 0, 0, 0.3);
  font-size: 13px;
}

.mymsgdiv {
  display: block;
  overflow: hidden;
  padding-bottom: 10px;
}

.mymsgdiv > img {
  display: block;
  float: right;
}

.mymsgdiv > .msgtxt {
  text-align: end;
  float: right;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: fit-content;
  margin-right: 10px;
}
.sendbtn {
  position: absolute;
  top: 5px;
  right: 5px;
}
/* 消息内容的样式 */
#chatpage /deep/ .msgdiv img {
  display: inline-block;
  width: 100px;
  height: 100px;
}
#chatpage /deep/ .msgdiv p {
  margin: 0;
  padding: 0;
}
#chatpage /deep/ #emoji-palette {
  top: -234px !important;
  left: -1px !important;
  max-width: 586px !important;
}
#chatpage /deep/ #tab-panel {
  height: 155px;
}
.item {
  margin-top: 10px;
  margin-right: 20px;
}
.chat-con-r {
  width: 299px;
  position: relative;
}
.chatuserinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.chatuserinfo > p {
  text-align: center;
}
.chatuserinfo > img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
.el-icon-time {
  position: absolute;
  left: 98px;
  top: 13px;
  font-size: 19px;
  cursor: pointer;
}
.his-item {
  width: 100%;
  box-sizing: border-box;
  padding-left: 10px;
}
.his-item > p {
  color: blue;
  font-size: 13px;
  padding: 0;
  margin: 5px 0 5px 0;
}

.his-item > span {
  font-size: 16px;
  margin-top: 6px;
}
.history {
  width: 259px;
  margin-top: 10px;
  position: absolute;
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  scrollbar-width: none;
}

.history::-webkit-scrollbar {
  width: 0;
}
</style>